<template>
  <div>
    <InfoTable
      title="虚拟号码信息"
      :data="filteredVirtualNumbers"
      :columns="columns"
      :pagination="pagination"
      key-field="virtualNumber"
      search-placeholder="请输入虚拟号码或绑定手机号"
      create-button-text="创建虚拟号码"
      :selected-items="selectedVirtualNumbers"
      @search="handleSearch"
      @create="handleCreate"
      @action="handleAction"
      @page-change="handlePageChange"
      @batch-delete="handleBatchDelete"
      @toggle-item-selection="toggleVirtualNumberSelection"
      @toggle-select-all="toggleSelectAll"
      @clear-selection="clearSelection"
    />
    
    <!-- 创建/编辑虚拟号码弹窗 -->
    <CreateVirtualNumber 
      v-model:visible="showCreateDialog"
      :is-edit="isEdit"
      :edit-id="currentEditId"
      :edit-data="currentEditData"
      @success="handleCreateSuccess"
    />
  </div>
</template>

<script>
import InfoTable from '@/components/InfoTable.vue'
import CreateVirtualNumber from './CreateVirtualNumber.vue'
import { getVirtualNumberInfo, deleteVirtualNumberInfo, deleteBatchVirtualNumberInfo } from '@/apis/virtualNumber'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'VirtualNumberInfoTemplate',
  components: {
    InfoTable,
    CreateVirtualNumber
  },
  data() {
    return {
      allVirtualNumbers: [],
      searchQuery: '',
      loading: false,
      selectedVirtualNumbers: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        { key: 'virtualNumber', title: '虚拟号码' },
        { key: 'level', title: '等级' },
        { key: 'rate', title: '费率' },
        { key: 'ownerPhone', title: '绑定手机号' },
        { key: 'status', title: '状态', format: 'status' },
        { key: 'createTime', title: '创建时间' },
        { key: 'updateTime', title: '更新时间' }
      ],
      showCreateDialog: false,
      isEdit: false,
      currentEditId: null,
      currentEditData: null
    }
  },
  computed: {
    // 分页后的虚拟号码数据
    paginatedVirtualNumbers() {
      const start = (this.pagination.current - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredVirtualNumbers.slice(start, end);
    },
    // 根据搜索条件过滤后的虚拟号码数据
    filteredVirtualNumbers() {
      let filtered = this.allVirtualNumbers;
      
      // 如果有搜索查询，按搜索结果筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.trim().toLowerCase();
        filtered = filtered.filter(virtualNumber => 
          (virtualNumber.virtualNumber && virtualNumber.virtualNumber.toLowerCase().includes(query)) ||
          (virtualNumber.ownerPhone && virtualNumber.ownerPhone.toLowerCase().includes(query))
        );
      }
      
      return filtered;
    },
    // 检查是否所有项目都被选中
    areAllItemsSelected() {
      return this.paginatedVirtualNumbers.length > 0 && 
             this.selectedVirtualNumbers.length === this.paginatedVirtualNumbers.length;
    }
  },
  methods: {
    async loadVirtualNumberData() {
      this.loading = true;
      try {
        const res = await getVirtualNumberInfo();
        console.log('虚拟号码数据:', res);
        // 根据后端接口返回的数据结构处理数据
        if (res && res.code === 0 && res.data) {
          // 直接使用后端返回的 data 数据
          this.allVirtualNumbers = Array.isArray(res.data) ? res.data : [];
          this.pagination.total = this.allVirtualNumbers.length;
        }
      } catch (error) {
        console.error('获取虚拟号码数据失败:', error);
        // 出错时清空数据
        this.allVirtualNumbers = [];
        ElMessage.error('获取虚拟号码数据失败');
      } finally {
        this.loading = false;
      }
    },
    handleSearch(query) {
      console.log('搜索虚拟号码:', query);
      this.searchQuery = query;
      // 重置到第一页
      this.pagination.current = 1;
    },
    handleCreate() {
      console.log('创建虚拟号码');
      this.isEdit = false;
      this.currentEditId = null;
      this.currentEditData = null;
      this.showCreateDialog = true;
    },
    handleCreateSuccess() {
      this.loadVirtualNumberData();
    },
    handleAction({ action, item }) {
      switch (action) {
        case 'view':
          console.log('查看虚拟号码:', item);
          ElMessage.info(`查看虚拟号码: ${item.virtualNumber}`);
          break;
        case 'edit':
          console.log('编辑虚拟号码:', item);
          this.isEdit = true;
          this.currentEditId = item.id;
          this.currentEditData = item; // 传递原始数据
          this.showCreateDialog = true;
          break;
        case 'delete':
          console.log('删除虚拟号码:', item);
          this.handleDelete(item);
          break;
      }
    },
    handleDelete(item) {
      ElMessageBox.confirm(
        `确定要删除虚拟号码 ${item.virtualNumber} 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const res = await deleteVirtualNumberInfo(item.virtualNumber);
          if (res && res.code === 0) {
            ElMessage.success('删除成功');
            this.loadVirtualNumberData();
            // 从选中项中移除
            const index = this.selectedVirtualNumbers.indexOf(item.virtualNumber);
            if (index > -1) {
              this.selectedVirtualNumbers.splice(index, 1);
            }
          } else {
            ElMessage.error(res?.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除虚拟号码失败:', error);
          ElMessage.error('删除虚拟号码失败');
        }
      }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除');
      });
    },
    handlePageChange(page) {
      console.log('切换到页面:', page);
      this.pagination.current = page;
      // 清除选中项
      this.clearSelection();
    },
    // 处理批量删除
    handleBatchDelete(selectedItems) {
      console.log('批量删除虚拟号码:', selectedItems);
      if (selectedItems.length === 0) {
        ElMessage.warning('请选择要删除的虚拟号码');
        return;
      }
      
      ElMessageBox.confirm(
        `确定要删除选中的 ${selectedItems.length} 个虚拟号码吗？`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // selectedItems 现在是选中项的 virtualNumber 数组，可以直接使用
          const res = await deleteBatchVirtualNumberInfo(selectedItems);
          if (res && res.code === 0) {
            ElMessage.success('批量删除成功');
            this.loadVirtualNumberData();
            // 清除选中项
            this.selectedVirtualNumbers = [];
          } else {
            ElMessage.error(res?.msg || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除虚拟号码失败:', error);
          ElMessage.error('批量删除虚拟号码失败');
        }
      }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消批量删除');
      });
    },
    // 切换项目选择状态
    toggleVirtualNumberSelection(virtualNumber) {
      const index = this.selectedVirtualNumbers.indexOf(virtualNumber);
      if (index > -1) {
        // 如果已选中，则取消选中
        this.selectedVirtualNumbers.splice(index, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedVirtualNumbers.push(virtualNumber);
      }
    },
    // 切换全选状态
    toggleSelectAll() {
      if (this.selectedVirtualNumbers.length === this.paginatedVirtualNumbers.length) {
        // 如果已全选，则取消全选
        this.selectedVirtualNumbers = [];
      } else {
        // 如果未全选，则全选当前页的所有项目
        this.selectedVirtualNumbers = this.paginatedVirtualNumbers.map(item => item.virtualNumber);
      }
    },
    // 清除选中项
    clearSelection() {
      this.selectedVirtualNumbers = [];
    }
  },
  mounted() {
    this.loadVirtualNumberData();
  },
  watch: {
    allVirtualNumbers() {
      // 数据变化时更新总数量
      this.pagination.total = this.allVirtualNumbers.length;
      // 数据变化时清除选中项中已不存在的项
      this.selectedVirtualNumbers = this.selectedVirtualNumbers.filter(virtualNumber => 
        this.allVirtualNumbers.some(item => item.virtualNumber === virtualNumber)
      );
    }
  }
}
</script>

<style scoped>
</style>